<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>列表排序</title>
</head>
<body>
    <div id="app">
      <h3>人员信息</h3>
        <p><input v-model="keyword" placeholder="搜索"></p>
        <button @click="sortNum=1">按年龄升序</button>
        <button @click="sortNum=2">按年龄降序</button>
        <button @click="sortNum=0">原样显示</button>
      <ul>
        <li v-for="item in newPeoples" :key="item.id">
          {{item.id}}---{{item.name}}---{{item.sex>0?"女":"男"}}---{{item.age}}
        </li>
      </ul>
    </div>

<script src="../js/vue.js"></script>
    <script type="text/javascript">
      const vm=new Vue({
        el:"#app",
        data(){
          return{
            //初始数据
            persons:[
              {id:"001",name:"马冬梅",sex:1,age:18},
              {id:"002",name:"周冬雨",sex:1,age:40},
              {id:"003",name:"周杰伦",sex:0,age:34},
              {id:"004",name:"林俊杰",sex:0,age:11},
            ],
            //过滤后的数据
            filPersons:[],
            //关键字
            keyword:"",
              //排序标识
              sortNum:0
          }
        },
        //使用监视属性实现列表过滤
        //region
        // watch:{
        //   keyword:{
        //     immediate:true,
        //     handler(val){
        //         this.filPersons=this.persons.filter((p)=>{
        //          return p.name.indexOf(val)!==-1
        //         })
        //     }
        //   }
        // }
        //endRegion

        //使用计算属性实现列表过滤并排序
        computed:{
            newPeoples(compareFn){
            let arr= this.persons.filter((p)=>{
              return p.name.indexOf(this.keyword)!==-1
            })
                if (this.sortNum){
                    arr.sort((a,b)=>{
                        return this.sortNum===1?a.age-b.age:b.age-a.age;
                    })
                }
                return arr
          }
      }
      })
    </script>
</body>
</html>
